<?php
/**
 * Created by PhpStorm.
 * User: Wei
 * Date: 17/10/5
 * Time: 11:54
 */


class DBHelper
{
    private $isProductionMode = false;
    private $db_config = [
        "dev" => [
            'dbms' => 'mysql',     //数据库类型
            'host' => 'localhost', //数据库主机名
            'dbName' => 'mimi',    //使用的数据库
            'user' => 'root',      //数据库连接用户名
            'pass' => 'root',          //对应的密码
        ],
        "production" => [
            'dbms' => 'mysql',     //数据库类型
            'host' => 'hdm32560788.my3w.com', //数据库主机名
            'dbName' => 'hdm32560788_db',    //使用的数据库
            'user' => 'hdm32560788',      //数据库连接用户名
            'pass' => 'Python52000',          //对应的密码
        ]
    ];
    private $dbConfig;

    public function __construct()
    {
        $this->dbConfig = $this->db_config[!$this->isProductionMode ? "dev" : "production"];
        $this->dbms = $this->dbConfig['dbms'];
        $this->host = $this->dbConfig['host'];
        $this->dbName = $this->dbConfig['dbName'];
        $this->user = $this->dbConfig['user'];
        $this->pass = $this->dbConfig['pass'];

        $this->dsn = "$this->dbms:host=$this->host;dbname=$this->dbName";
    }

    public function select($sql)
    {
        try {
            $dbh = new PDO($this->dsn, $this->user, $this->pass); //初始化一个PDO对象
            //默认这个不是长连接，如果需要数据库长连接，需要最后加一个参数：array(PDO::ATTR_PERSISTENT => true) 变成这样：
            //$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));
//            echo '连接成功<br/>';
            $selectNodesSql = $sql;
            $arr = [];
            $result = $dbh->query($selectNodesSql);

            foreach ($result as $row) {
                //array_push($arr, $row); //你可以用 echo($GLOBAL); 来看到这些值
                $arr[] = $row;
                //if ($count++ >= 9) break; /*经测试, 数量不可太大, 否则 502*/
            }

            $dbh = null;
            $data = array("result" => $arr);
            return $data;

        } catch (PDOException $e) {
            die ("Error!: " . $e->getMessage() . "<br/>");
        }
    }
}